package com.ruoyi.chat.LongConnection.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.chat.LongConnection.handler.nettyService.HasChannelChatService;
import com.ruoyi.chat.LongConnection.handler.nettyService.NonChannelChatService;
import com.ruoyi.chat.LongConnection.model.LongConnectionChatDTO;
import com.ruoyi.chat.LongConnection.model.ReturnMsgVo;
import com.ruoyi.chat.LongConnection.util.LongConnectionMsgUtil;
import com.ruoyi.chat.LongConnection.util.LongConnectionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;

/**
 * @author MaTaoxun
 * @package: com.ruoyi.chat.LongConnection.handler
 * @className: ChatHandler
 * @description: 聊天handler
 * @date 2021/9/28 23:05
 */

public class ChatHandler extends SimpleChannelInboundHandler<String> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        ObjectMapper mapper = new ObjectMapper();
        LongConnectionChatDTO chatDTO = null;
        try {
            chatDTO = mapper.readValue(msg, LongConnectionChatDTO.class);
        } catch (Exception e) {
            ctx.writeAndFlush(LongConnectionMsgUtil.ObjectToWSTextResult(new ReturnMsgVo(ReturnMsgVo.WRONG_PACKAGE, "数据包结构错误")));
            return;
        }
        // 未完成：需要检查投递的id是否存在

        SocketChannel channel = LongConnectionUtil.getChannelById(chatDTO.getReceiverId());
        if (channel == null) {
            String senderId = LongConnectionUtil.getIdByChannel((SocketChannel) ctx.channel());
            NonChannelChatService.doChat(chatDTO.getMsgType(),ctx,chatDTO,senderId);
        } else {
            String senderId = LongConnectionUtil.getIdByChannel((SocketChannel) ctx.channel());
            HasChannelChatService.doChat(chatDTO.getMsgType(),ctx,chatDTO,senderId);
        }
        ctx.fireChannelRead(msg);
    }


}
